package org.unigram.oluolu.recommend;

import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Mapper.Context;

/**
 *
 */
public class ExtractRelatedUsersMapper extends
        Mapper<LongWritable, Text, LongWritable, LongWritable> {
    
    /**
     * map method implements Mapper interface.
     * 
     * @param dummy no use
     * @param value value
     * @param context write down key value
     * 
     * @throws IOException -
     * @throws InterruptedException -
     */
    @Override
    public final void map(final LongWritable dummy,
            final Text value, final Context context)
            throws IOException, InterruptedException {
        
        String inputStr = value.toString();        
        try {
            String[] inputArray = inputStr.split("\t");
            this.processRecommendations(inputArray[1], context);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("PARSING ERROR in line: " + inputStr);
            e.printStackTrace();
        }        
     }

    /**
     * create related user pairs.
     * 
     * @param idsStr set of users in the same cluster
     * @param context write the user pairs
     * @throws NumberFormatException -
     * @throws IOException -
     * @throws InterruptedException -
     */
    private void processRecommendations(final String idsStr, 
            final Context context) throws NumberFormatException, 
            IOException, InterruptedException {
        String[] idsArray = idsStr.split(" "); // ids in the cluster.
        for (int i=0; i<idsArray.length; i++) {
            for (int j=0; j<idsArray.length; j++) {
                if (i == j) {
                    continue;
                }
                context.write(new LongWritable(Long.parseLong(idsArray[i])), 
                        new LongWritable(Long.parseLong(idsArray[j])));
            }
        }
    }
}
